from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse



# Create your views here.
from .. import models
import time
# 文件上传
from web.settings import BASE_DIR
# 密码加密
from django.contrib.auth.hashers import make_password, check_password
import os
# 数据分页需导入
from django.core.paginator import Paginator
# 导入Q对象
from django.db.models import Q
from . viewsIndex import uploads



# 后台会员添加
def useradd(request):
    
    # 判断当前的请求方式
    if request.method == 'GET':
        return render(request,'myadmin/users/add.html')
    elif request.method == "POST":
        try:
            # 接收数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            # 密码加密
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')

            # 头像上传
            myfile = request.FILES.get('pic_url')
            if myfile:
                # 调用函数进行头像上传
                data['pic_url'] = uploads(myfile)
            # 默认头像
            else:
                data['pic_url'] = '/static/pics/user.jpg'

            # 进行数据的添加
            ob = models.Users(**data)
            # print(data)
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_user_add')+'"</script>')


# 显示后台信息
def userindex(request):

    # 获取所有的用户数据
    data = models.Users.objects.filter().exclude(status = 3)
    # ------------------搜索---------------------
    # 
    # 获取搜索条件和数据
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == "all":
            # Q 对象 <===> or   filter <====>  and
            data = data.filter(Q(username__contains = keywords)|Q(id__contains = keywords)|Q(phone__contains = keywords)|Q(email__contains = keywords)|Q(age__contains = keywords))
        elif types == 'id':
            if keywords.isdigit():
                data = data.filter(id = keywords)
            else:
                return HttpResponse('<script>alert("查询失败");location.href="'+reverse('myadmin_user_index')+'"</script>')
        elif types == 'age':
            if keywords.isdigit():
                data = data.filter(age = keywords)
            else:
                return HttpResponse('<script>alert("查询失败");location.href="'+reverse('myadmin_user_index')+'"</script>')
        elif types == 'status':
            arr = {'正常':0,'禁用':1,'删除':3}
            if keywords in arr:
                data=data.filter(status=arr[keywords])
            else:
                return HttpResponse('<script>alert("查询失败");location.href="'+reverse('myadmin_user_index')+'"</script>')

        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)
    # ---------------------------------------
  
    # ----------------数据分页-----------------------
    # 
    # 实例化分页类  参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data,10)

    # 获取当前页码数 ===> ?p=n
    p = request.GET.get('p',1)
    # 获取当前页的数据
    userlist = paginator.page(p)
    # page_range  能得到页码数的区间
    print(paginator.page_range)
    # ---------------------------------------

    # 分配数据
    context = {'userlist':userlist}
    return render(request,'myadmin/users/index.html',context)



# 删除后台会员 逻辑删除
def userdel(request,uid):
    try:
        # 根据uid获取用户对象,修改状态
        ob = models.Users.objects.get(id = uid)
        ob.status = 3
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_user_index')+'"</script>')

# 修改后台会员信息
def useredit(request,uid):
    # 根据uid显示编辑对象
    ob = models.Users.objects.get(id = uid)
    # 判断请求方式
    if request.method == 'GET':
        # 显示编辑列表
        return render(request,'myadmin/users/edit.html',{'uinfo':ob})

    elif request.method == 'POST':
        # 执行判断
        ob.username = request.POST['username']
        # 判断密码
        # 密码为空,则是未修改密码,否则修改了密码
        if request.POST.get('password'):
            ob.password = make_password(request.POST.get('password'),None,'pbkdf2_sha256')
        ob.phone = request.POST.get('phone')
        ob.email = request.POST.get('email')
        ob.sex = request.POST.get('sex')
        ob.age = request.POST.get('age')
        # 判断是否更新了头像
        myfile = request.FILES.get('pic_url')
        if myfile:
            # 如果修改了头像,要上传新的头像,并判断是否删除以前头像
            if ob.pic_url != '/static/pics/user.jpg':
                try:
                    # 删除原来上传的头像
                    os.remove(BASE_DIR+ob.pic_url)
                except:
                    pass
            # 更新头像
            ob.pic_url = uploads(myfile)

        ob.save()

        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_user_index')+'"</script>')






